<?php
/**
 * 报单系统安装脚本
 */

// 检查是否已经安装
if (file_exists(__DIR__ . '/config.php') && file_exists(__DIR__ . '/functions.php')) {
    header('Location: index.php');
    exit;
}

// 默认配置
$defaultConfig = <<<EOF
<?php
/**
 * 报单系统配置文件
 */

// 数据库配置
define('DB_HOST', 'localhost');
define('DB_PORT', '3306');
define('DB_NAME', 'baodan_system');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');

// 应用配置
define('APP_URL', 'http://' . \$_SERVER['HTTP_HOST']);
define('UPLOAD_PATH', __DIR__ . '/uploads/');
define('UPLOAD_URL', APP_URL . '/uploads/');

// PushPlus配置
define('PUSHPLUS_API_URL', 'http://www.pushplus.plus/send');

// 开启session
session_start();

// 时区设置
date_default_timezone_set('Asia/Shanghai');
EOF;

// 处理安装表单
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $dbHost = $_POST['db_host'] ?? 'localhost';
    $dbPort = $_POST['db_port'] ?? '3306';
    $dbName = $_POST['db_name'] ?? 'baodan_system';
    $dbUsername = $_POST['db_username'] ?? 'root';
    $dbPassword = $_POST['db_password'] ?? '';
    $adminPhone = $_POST['admin_phone'] ?? '';
    $adminPassword = $_POST['admin_password'] ?? '';
    
    // 验证必填字段
    if (empty($dbHost) || empty($dbName) || empty($adminPhone) || empty($adminPassword)) {
        $error = '请填写所有必填字段';
    } elseif (strlen($adminPassword) < 6) {
        $error = '管理员密码长度不能少于6位';
    } else {
        try {
            // 测试数据库连接
            $dsn = "mysql:host=$dbHost;port=$dbPort;charset=utf8mb4";
            $pdo = new PDO($dsn, $dbUsername, $dbPassword);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            
            // 创建数据库
            $pdo->exec("CREATE DATABASE IF NOT EXISTS `$dbName` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
            $pdo->exec("USE `$dbName`");
            
            // 创建表结构
            $sql = file_get_contents(__DIR__ . '/database.sql');
            $pdo->exec($sql);
            
            // 创建更新脚本
            $updateSql = file_get_contents(__DIR__ . '/database_update.sql');
            $pdo->exec($updateSql);
            
            // 更新管理员密码
            $hashedPassword = password_hash($adminPassword, PASSWORD_BCRYPT);
            $stmt = $pdo->prepare("UPDATE users SET phone = ?, password = ? WHERE is_admin = 1");
            $stmt->execute([$adminPhone, $hashedPassword]);
            
            // 创建配置文件
            $configContent = str_replace([
                'localhost',
                '3306',
                'baodan_system',
                'root',
                "''"
            ], [
                $dbHost,
                $dbPort,
                $dbName,
                $dbUsername,
                "'" . addslashes($dbPassword) . "'"
            ], $defaultConfig);
            
            file_put_contents(__DIR__ . '/config.php', $configContent);
            
            // 创建必要的目录
            $dirs = [
                'uploads',
                'uploads/orders',
                'uploads/qrcodes',
                'uploads/settlements'
            ];
            
            foreach ($dirs as $dir) {
                $dirPath = __DIR__ . '/' . $dir;
                if (!is_dir($dirPath)) {
                    mkdir($dirPath, 0777, true);
                }
            }
            
            $success = '安装成功！系统已准备就绪。';
            
        } catch (Exception $e) {
            $error = '安装失败：' . $e->getMessage();
        }
    }
}

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>报单系统安装</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap-icons/1.7.2/font/bootstrap-icons.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            padding: 20px 0;
        }
        
        .install-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        .install-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .install-body {
            padding: 40px;
        }
        
        .step-indicator {
            display: flex;
            justify-content: center;
            margin-bottom: 30px;
        }
        
        .step {
            display: flex;
            align-items: center;
            margin: 0 20px;
        }
        
        .step-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #e9ecef;
            color: #6c757d;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 10px;
        }
        
        .step.active .step-number {
            background: #007bff;
            color: white;
        }
        
        .step.completed .step-number {
            background: #28a745;
            color: white;
        }
        
        .feature-list {
            list-style: none;
            padding: 0;
        }
        
        .feature-list li {
            padding: 10px 0;
            border-bottom: 1px solid #eee;
            display: flex;
            align-items: center;
        }
        
        .feature-list li:last-child {
            border-bottom: none;
        }
        
        .feature-list i {
            color: #28a745;
            margin-right: 10px;
            font-size: 1.2rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-8">
                <div class="install-container">
                    <div class="install-header">
                        <h1><i class="bi bi-box-seam"></i> 报单系统安装</h1>
                        <p class="mb-0">专业的订单管理与结算平台</p>
                    </div>
                    
                    <div class="install-body">
                        <?php if (isset($success)): ?>
                            <div class="text-center">
                                <div class="mb-4">
                                    <i class="bi bi-check-circle text-success" style="font-size: 4rem;"></i>
                                </div>
                                <h3 class="text-success mb-3"><?php echo htmlspecialchars($success); ?></h3>
                                <p class="text-muted mb-4">系统已成功安装并配置完成，现在您可以开始使用报单系统了。</p>
                                
                                <div class="alert alert-info">
                                    <h5>管理员登录信息</h5>
                                    <p><strong>手机号：</strong><?php echo htmlspecialchars($adminPhone); ?></p>
                                    <p><strong>密码：</strong>您设置的密码</p>
                                    <p class="mb-0"><a href="index.php" class="btn btn-primary">立即登录</a></p>
                                </div>
                                
                                <div class="mt-4">
                                    <h5>系统特色功能</h5>
                                    <ul class="feature-list">
                                        <li><i class="bi bi-check"></i>支持多种收货地和下单平台配置</li>
                                        <li><i class="bi bi-check"></i>灵活的付款方式选择（自己付款/群主垫付）</li>
                                        <li><i class="bi bi-check"></i>智能的结算管理（佣金/本金+佣金）</li>
                                        <li><i class="bi bi-check"></i>批量查询订单状态</li>
                                        <li><i class="bi bi-check"></i>实时推送通知</li>
                                        <li><i class="bi bi-check"></i>完善的权限管理</li>
                                    </ul>
                                </div>
                            </div>
                        <?php else: ?>
                            <div class="step-indicator">
                                <div class="step active">
                                    <div class="step-number">1</div>
                                    <div>数据库配置</div>
                                </div>
                                <div class="step">
                                    <div class="step-number">2</div>
                                    <div>管理员设置</div>
                                </div>
                                <div class="step">
                                    <div class="step-number">3</div>
                                    <div>完成安装</div>
                                </div>
                            </div>
                            
                            <?php if (isset($error)): ?>
                                <div class="alert alert-danger">
                                    <i class="bi bi-exclamation-triangle-fill"></i> <?php echo htmlspecialchars($error); ?>
                                </div>
                            <?php endif; ?>
                            
                            <form method="POST">
                                <div class="row">
                                    <div class="col-md-6">
                                        <h5 class="mb-3"><i class="bi bi-database"></i> 数据库配置</h5>
                                        
                                        <div class="mb-3">
                                            <label for="db_host" class="form-label">数据库主机</label>
                                            <input type="text" class="form-control" id="db_host" name="db_host" 
                                                   value="localhost" required>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="db_port" class="form-label">数据库端口</label>
                                            <input type="text" class="form-control" id="db_port" name="db_port" 
                                                   value="3306" required>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="db_name" class="form-label">数据库名称</label>
                                            <input type="text" class="form-control" id="db_name" name="db_name" 
                                                   value="baodan_system" required>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="db_username" class="form-label">数据库用户名</label>
                                            <input type="text" class="form-control" id="db_username" name="db_username" 
                                                   value="root" required>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="db_password" class="form-label">数据库密码</label>
                                            <input type="password" class="form-control" id="db_password" name="db_password">
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-6">
                                        <h5 class="mb-3"><i class="bi bi-person-circle"></i> 管理员设置</h5>
                                        
                                        <div class="mb-3">
                                            <label for="admin_phone" class="form-label">管理员手机号 <span class="text-danger">*</span></label>
                                            <input type="tel" class="form-control" id="admin_phone" name="admin_phone" 
                                                   placeholder="请输入管理员手机号" required pattern="^1[3-9]\d{9}$">
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="admin_password" class="form-label">管理员密码 <span class="text-danger">*</span></label>
                                            <input type="password" class="form-control" id="admin_password" name="admin_password" 
                                                   placeholder="请输入管理员密码" required minlength="6">
                                        </div>
                                        
                                        <div class="alert alert-info">
                                            <h6><i class="bi bi-info-circle"></i> 安装说明</h6>
                                            <ul class="mb-0">
                                                <li>确保MySQL服务正在运行</li>
                                                <li>数据库用户需要有创建数据库的权限</li>
                                                <li>安装完成后请删除此文件</li>
                                                <li>建议定期备份数据库</li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="text-center mt-4">
                                    <button type="submit" class="btn btn-primary btn-lg">
                                        <i class="bi bi-download"></i> 开始安装
                                    </button>
                                </div>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
</body>
</html>